import express from 'express'
import { Response, Request } from "express"

const router = express.Router()

import { success, failure } from '../utils/responses'
import { AppDataSource } from "../config/database"
import { Post } from "../entities/Post";
import { AuthRequest } from "../middlewares/user-auth";
import { User } from "../entities/User";
import { In } from "typeorm";

/**
 * 查询动态列表
 */
router.get('/', async function (req: Request, res: Response) {
  try {
    const query = req.query

    const currentPage = Math.abs(Number(query.currentPage)) || 1 // 当前页
    const pageSize = Math.abs(Number(query.pageSize)) || 10 // 每页条数
    const offset = (currentPage - 1) * pageSize // 偏移量

    const userId = (req as AuthRequest).id as string
    const userRepository = AppDataSource.getRepository(User)

    // 获取当前登录用户
    const user = await userRepository.findOne({
      where: { id: userId },
      relations: { followings: true } // 必须要加载followings，否则user实体没有followings字段
    })

    // 收集关注者的id
    const followingsList = user.followings.map(following => following.id)

    // 添加自己的id，因为动态也需要展示自己的动态
    followingsList.push(userId)

    const postRepository = AppDataSource.getRepository(Post)
    const [posts, totalCount] = await postRepository.findAndCount({
      where: { authorId: In(followingsList) },
      relations: {
        author: true,
        comment: true
      },
      order: { updatedAt: "DESC" }, // 按照发布时间降序排列
      skip: offset,
      take: pageSize,
    })

    // 去除不需要的字段
    const filterPosts = posts.map(post => {
      const { id, title, content, likeCount, comment, shareCount, updatedAt, author } = post;
      return {
        id,
        title,
        content,
        likeCount,
        commentCount: comment.length,
        shareCount,
        updatedAt,
        author: {
          id: author.id,
          username: author.username,
          avatar: author.avatar
        }
      }
    })


    success(res, '查询动态列表成功', {
      posts: filterPosts,
      pagination: {
        totalPage: Math.ceil(totalCount / pageSize),
        currentPage,
        pageSize,
        totalCount
      }
    })
  } catch (error) {
    failure(res, error)
  }
})

export default router;
